/*
 *  Copyright (C) 2010 Zubanov Dmitry
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 *
 * @author Zubanov Dmitry aka javadimon, zubanov@gmail.com
 * Omsk, Russia, created 29.05.2010
 * (C) Copyright by Zubanov Dmitry
 */
package org.jssdb.core.filesystem;

import java.util.*;
import java.io.*;

public abstract class DirWatcher extends TimerTask {

    private String path;
    private File filesArray[];
    private HashMap dir = new HashMap();
    private DirFilterWatcher dfw;
    private static int ADD = 0, MODIFY = 1, DELETE = 2;

    public DirWatcher(String path) {
        this(path, "");
    }

    public DirWatcher(String path, String filter) {
        this.path = path;
        dfw = new DirFilterWatcher(filter);
        filesArray = new File(path).listFiles(dfw);

        // transfer to the hashmap be used a reference and keep the
        // lastModfied value
        for (int i = 0; i < filesArray.length; i++) {
            dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
        }
    }

    public final void run() {
        HashSet checkedFiles = new HashSet();
        filesArray = new File(path).listFiles(dfw);

        // scan the files and check for modification/addition
        for (int i = 0; i < filesArray.length; i++) {
            Long current = (Long) dir.get(filesArray[i]);
            checkedFiles.add(filesArray[i]);
            if (current == null) {
                // new file
                dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
                onChange(filesArray[i], ADD);
            } else if (current.longValue() != filesArray[i].lastModified()) {
                // modified file
                dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
                onChange(filesArray[i], MODIFY);
            }
        }

        // now check for deleted files
        Set ref = ((HashMap) dir.clone()).keySet();
        ref.removeAll((Set) checkedFiles);
        Iterator it = ref.iterator();
        while (it.hasNext()) {
            File deletedFile = (File) it.next();
            dir.remove(deletedFile);
            onChange(deletedFile, DELETE);
        }
    }

    protected abstract void onChange(File file, int action);
}
